package com.gxsf.wechatbook.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxsf.wechatbook.pojo.MarkSpeak;
import com.gxsf.wechatbook.pojo.TokenList;
import com.gxsf.wechatbook.pojo.User;
import com.gxsf.wechatbook.pojo.UserSmsList;
import com.gxsf.wechatbook.repo.MarkSpeakRepository;
import com.gxsf.wechatbook.repo.TokenListRepository;
import com.gxsf.wechatbook.repo.UserRepository;
import com.gxsf.wechatbook.repo.UserSmsListRepository;
import com.gxsf.wechatbook.service.UserService;
import com.gxsf.wechatbook.token.UserLoginToken;
import com.gxsf.wechatbook.util.Error;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping({"/user_json"})
@CrossOrigin
@RestController
@Api(
        tags = {"user_json 用户相关接口"},
        description = "提供用户相关的,后缀[.opera]表述操作接口,[.json]表示信息接口"
)
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    UserService userService;
    @Autowired
    TokenListRepository tokenListRepository;
    @Autowired
    UserSmsListRepository userSmsListRepository;
    @Autowired
    MarkSpeakRepository markSpeakRepository;
    @Autowired
    UserRepository userRepository;

    @ApiOperation("登录,传参phone和password")
    @PostMapping({"/login.opera"})
    public String login(@RequestBody Map<String, String> map) {
        String phone = (String)map.get("phone");
        String password = (String)map.get("password");
        return this.userService.login(phone, password);
    }

    @ApiOperation("注册,传参phone,name,password,college,realName.分别对应：手机号，昵称，密码，专业，真实姓名")
    @PostMapping({"/join.opera"})
    public Object join(@RequestBody Map<String, String> map) {
        String phone = (String)map.get("phone");
        String name = (String)map.get("name");
        String password = (String)map.get("password");
        password = DigestUtils.md5Hex(password.getBytes(StandardCharsets.UTF_8)).toUpperCase();
        String college = (String)map.get("college");
        String realName = (String)map.get("realName");
        if (college != null && !college.isEmpty()) {
            User byPhone = this.userRepository.findByPhone(Long.parseLong(phone));
            if (byPhone != null) {
                return Error.error(403, "该手机号已被注册");
            } else {
                User user = new User();
                user.setCollege(college);
                user.setCreateTime(new Timestamp(System.currentTimeMillis()));
                user.setPhone(Long.parseLong(phone));
                user.setName(name);
                user.setPassword(password);
                user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                user.setRealName(realName);
                return this.userRepository.save(user);
            }
        } else {
            return Error.error(403, "你有未填写的参数");
        }
    }

    @UserLoginToken
    @ApiOperation("根据token退出登录")
    @PostMapping({"/exit.opera"})
    public void exit(HttpServletRequest request) {
        String token = request.getHeader("token");
        this.tokenListRepository.deleteByTokenName(token);
    }

    @UserLoginToken
    @ApiOperation("根据token获取用户信息")
    @PostMapping({"/getUser.json"})
    public User userInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        TokenList tokenList = this.tokenListRepository.findFirst1ByTokenNameAndStatusOrderByTokenIdDesc(token, 0L);
        String message = tokenList.getMessage();
        JSONObject jsonObject = JSON.parseObject(message);
        return (User)JSON.toJavaObject(jsonObject, User.class);
    }

    @UserLoginToken
    @ApiOperation("修改密码")
    @PostMapping({"/updatePassword.opera"})
    public Object updatePassword(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String token = request.getHeader("token");
        String password = (String)map.get("password");
        String password_2 = (String)map.get("password_2");
        return password.equals(password_2) ? this.userService.updatePassword(token, password) : Error.error(404, "两次输入密码不一致");
    }

    @UserLoginToken
    @ApiOperation("修改昵称")
    @PostMapping({"/updateName.opera"})
    public Object updateName(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String token = request.getHeader("token");
        String name = (String)map.get("name");
        return this.userService.updateName(token, name);
    }

    @UserLoginToken
    @ApiOperation("用户的信箱")
    @PostMapping({"/sms.json/{userId}"})
    public List<UserSmsList> sms(@PathVariable("userId") String userId) {
        return this.userSmsListRepository.findAllByUserId(Long.parseLong(userId));
    }

    @UserLoginToken
    @ApiOperation("信箱设置已读")
    @PostMapping({"/smsYd.opera/{smsId}"})
    public void smsYd(@PathVariable("smsId") String smsId) {
        Optional<UserSmsList> byId = this.userSmsListRepository.findById(Long.parseLong(smsId));
        if (byId.isPresent()) {
            UserSmsList userSmsList = (UserSmsList)byId.get();
            userSmsList.setStatus(1);
            this.userSmsListRepository.save(userSmsList);
        }

    }

    @UserLoginToken
    @ApiOperation("用户的吐槽")
    @PostMapping({"/markSpeak.json"})
    public void markSpeak(@RequestBody Map<String, String> map) {
        String userId = (String)map.get("userId");
        String content = (String)map.get("content");
        MarkSpeak markSpeak = new MarkSpeak();
        markSpeak.setUserId(Long.parseLong(userId));
        markSpeak.setContent(content);
        markSpeak.setCreateTime(new Timestamp(System.currentTimeMillis()));
        markSpeak.setStatus(0);
        this.markSpeakRepository.save(markSpeak);
    }

    @UserLoginToken
    @ApiOperation("用户的头像")
    @PostMapping({"/userAvatar.json/{userId}"})
    public String userAvatar(@PathVariable("userId") long userId) {
        Optional<User> byId = this.userRepository.findById(userId);
        if (byId.isPresent()) {
            User user = (User)byId.get();
            return user.getAvatar();
        } else {
            return null;
        }
    }
}
